package com.dynamic.mybatis.autoconfigure;

import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.dynamic.mybatis.core.datasource.DynamicMultipleDataSource;
import com.dynamic.mybatis.core.metadata.DynamicConfiguration;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({DynamicMybatisProperties.class})
//@ConditionalOnSingleCandidate(DataSource.class)

public class DynamicMybatisAutoConfig {
    private static final Log log = LogFactory.getLog(DynamicMybatisAutoConfig.class);


    @Bean
    //@ConditionalOnBean(DataSource.class)
    // @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory(DynamicMybatisProperties properties) throws Exception {
        log.debug("create sqlSessionFactory");
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        //数据源
        sqlSessionFactoryBean.setDataSource(new DynamicMultipleDataSource());
        //mybatis配置
        sqlSessionFactoryBean.setTypeAliasesPackage(properties.getTypeAliasesPackage());
        sqlSessionFactoryBean.setMapperLocations(properties.resolveMapperLocations());
        //mybatis Configuration 配置
        DynamicConfiguration configuration = properties.getConfiguration();
        sqlSessionFactoryBean.setObjectWrapperFactory(new MybatisMapWrapperFactory());
        sqlSessionFactoryBean.setConfiguration(configuration);
        //设置不生成短id
        configuration.setUseGeneratedShortKey(Boolean.FALSE);
        return sqlSessionFactoryBean.getObject();
    }


    @Bean
    @ConditionalOnBean(SqlSessionFactory.class)
    @ConditionalOnMissingBean
    public SqlSessionTemplate sqlSessionTemplate(DynamicMybatisProperties properties) throws Exception {
        log.debug("create sqlSessionTemplate");
        SqlSessionFactory sqlSessionFactory = sqlSessionFactory(properties);
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    @ConditionalOnBean(SqlSessionTemplate.class)
    @ConditionalOnMissingBean
    public DynamicSqlSessionTemplate dynamicSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate, SqlSessionFactory sqlSessionFactory) {
        log.debug("create dynamicSqlSessionTemplate");
        return new DynamicSqlSessionTemplate(sqlSessionFactory, sqlSessionTemplate);
    }


}